package tt.dz.egobus.servicemanager.facade.interator;

import tt.dz.egobus.servicemanager.core.exception.BusinessException;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Anson
 * @date 17-3-20
 * @name
 * @since 1.0.1
 */
public class InterceptorChain implements Interceptor {

    private List<Interceptor> chain = new ArrayList<Interceptor>();

    public void addChain(Interceptor interceptor) {
        this.chain.add(interceptor);
    }

    @Override
    public boolean interceptBefore(Object obj, Method method, Object[] args) throws BusinessException {
        boolean isSuccess = true;
        for (Interceptor interceptor : this.chain) {
            if (!(isSuccess = interceptor.interceptBefore(obj, method, args))) {
                break;
            }
        }
        return isSuccess;
    }

    @Override
    public Object interceptPost(Object obj, Method method, Object[] args, Object result) throws BusinessException {
        Object object = result;
        for (Interceptor interceptor : this.chain) {
            object = interceptor.interceptPost(obj, method, args, result);
        }
        return object;
    }
}
